import uuid
from flask import Blueprint, request, make_response, jsonify, redirect

from app import db
import json, random, time, requests,snowflake.client
from util.myredis import r
from models.user import *
from werkzeug.security import generate_password_hash,check_password_hash
from utils.myjwt import myjwt

shu_blue = Blueprint("shublue",__name__)

@shu_blue.route('/user_no_server')
def user_no_server():
    user_id = request.args.get('user_id')
    server = db.session.execute("""select count(status) as count,status from (select * from server union all select * from server1 union all select * from server2) as t where rob_id=%d and t.status in (3,4) group by t.status"""%(int(user_id)))
    list1 = []
    for i in server:
        if i.status == 3:
            name = "未完成"
        else:
            name = "已完成"
        list1.append({
            'value':i.count,
            'name':name
        })
    return jsonify({
        'code':200,
        'msg':"OK",
        'data':list1
    })


@shu_blue.route('/get_goods')
def get_goods():
    lst = []
    res = Goods.query.all()
    for i in res:
        lst.append({
            'id':i.id,
            'title':i.title,
            'desc':i.desc,
            'image':i.image,
            'money':i.money,
        })
    return jsonify({
        'code':200,
        'msg':"获取商品成功",
        'data':lst
    })

@shu_blue.route('/add_cart',methods=['POST'])
def add_cart():
        data = json.loads(request.data)
        user_id = data['user_id']
        goods_id = data['goods_id']
        cart_key = 'cart_' + str(user_id)
        num = r.getone_hash(cart_key,goods_id)
        if num:
            return jsonify({
                'code':200,
                'msg':"购物车商品已存在"
            })
        else:
            r.hash_add(cart_key,goods_id,'1')
            return jsonify({
                'code':200,
                'msg':"加入购物车成功"
            })

@shu_blue.route('/get_cart')
def get_cart():
    user_id = request.args.get('user_id')

    cart_key = 'cart_' + str(user_id)
    cart_goods = r.getall_hash(cart_key)
    cart_list = []

    for k,v in cart_goods.items():
        good = Goods.query.filter_by(id=int(k.decode())).first()
        cart_list.append({
            'id': good.id,
            'title': good.title,
            'desc': good.desc,
            'image': good.image,
            'money': good.money,
        })
    return jsonify({
        'code':200,
        'msg':"获取购物车成功",
        'data':cart_list
    })


@shu_blue.route('/m_token')
def m_token():
    # 生成token
    token = uuid.uuid1().hex
    print(token)
    # 将token保存redis
    r.add_str(token,'1')
    # 返回结果
    return jsonify({
        'code':200,
        'msg':"OK",
        'token':token
    })



@shu_blue.route('/buy_goods',methods=['POST'])
def buy_goods():
    data = json.loads(request.data)
    user_id = data['user_id']
    goods_id = data['goods_id']

    m_token = data['token']
    value = r.get_str(m_token)
    if not value:
        return jsonify({'code':400,'msg':"不能频繁操作"})
    # 删除
    r.del_key(m_token)

    cart_key = 'cart_' + str(user_id)
    if not all([user_id,goods_id]):
        return jsonify({
            'code':400,
            'msg':"参数错误"
        })
    rob_user = Users.query.filter_by(id=user_id).first()
    for i in goods_id:
        goods = Goods.query.filter_by(id=int(i)).first()
        goods_user = Users.query.filter_by(id=goods.user_id).first()
        if rob_user:
            if rob_user.id != goods_user.id:
                if rob_user.money > goods.money:
                    try:
                    # 修改拥有商品的用户表
                    # 修改用户表
                        if rob_user and goods_user:
                            goods_user.money = goods_user.money + goods.money
                            rob_user.money = rob_user.money - goods.money
                            db.session.add(rob_user)
                        # 添加购买订单表记录
                        orders = Orders(money=float(goods.money), status=2, user_id=user_id, goods_id=int(i))
                        db.session.add(orders)
                        db.session.commit()
                        r.del_hash(cart_key,i)
                    except Exception as e:
                        db.session.rollback()
                        print(e)
                        return jsonify({
                            'code':400,
                            'msg':"错误"
                        })
                else:
                    return jsonify({
                        'code': 402,
                        'msg': "余额不足请充值"
                    })
            else:
                return jsonify({
                    'code':400,
                    'msg':"不能购买自己发布的商品"
                })
        else:
            return jsonify({
                'code': 401,
                'msg': "请重新登录"
            })
    return jsonify({
        'code': 200,
        'msg': "购买成功"
    })














